import router from '@/router/router';
import store from '@/store/index';
import { MessageBox, Message, Loading  } from 'element-ui';
import { baseUrl } from '@/config/env';
import CryptoJS from 'crypto-js'
import JsBarcode from 'jsbarcode';
import request from '@/assets/js/http';

function util() {
    this.baseUrl = baseUrl;
    // 序列化转为对象
    this.format = (str) => {
        let arr = str.split('&');
        let obj = {};
        arr.forEach(item => {
            let item_arr = item.split('=')
            obj[item_arr[0]] = item_arr[1];
        });
        return obj;
    };

    // 对象转为序列化
    this.serialize = (obj) => {
        let str = '?';
        for(let key in obj){
            str += key + '=' + obj[key] + '&';
        };
        return str.slice(0, str.length-1);
    }

    // 筛选出有值的参数
    this.filterParams = (obj) => {
        let newObj = {};
        for(let key in obj){
            if(Array.isArray(obj[key])){
                if(obj[key].length > 0){
                    newObj[key] = obj[key]
                }
            }else{
                if(obj[key]){
                    newObj[key] = obj[key]
                }
            }
        }
        return newObj;
    }
    // 筛选不为[]和null的参数
    this.filterNull = (obj) => {
        let newObj = {};
        for(let key in obj){
            if(Array.isArray(obj[key])){
                if(obj[key].length > 0){
                    newObj[key] = obj[key]
                }
            }else{
                if(obj[key] != null){
                    newObj[key] = obj[key]
                }
            }
        }
        return newObj;
    }

    // 将毫秒转为时分秒
    this.formatDuring = (mss) => {
        var days = parseInt(mss / (1000 * 60 * 60 * 24));
        var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((mss % (1000 * 60)) / 1000);
        let str = '';
        if(hours == 0){
            str = minutes + "分钟 " + seconds + "秒 ";
        }else{
            str = hours + '小时' + minutes + "分钟" + seconds + "秒 ";
        }
        if(hours == 0 && minutes == 0){
            str = seconds + '秒'
        }
        return str;
    };

    // 将时间转为字符串
    this.dateToString = (now) => {
        var year = now.getFullYear();
        var month =(now.getMonth() + 1).toString();
        var day = (now.getDate()).toString();
        var hour = (now.getHours()).toString();
        var minute = (now.getMinutes()).toString();
        var second = (now.getSeconds()).toString();
        if (month.length == 1) {
            month = "0" + month;
        }
        if (day.length == 1) {
            day = "0" + day;
        }
        if (hour.length == 1) {
            hour = "0" + hour;
        }
        if (minute.length == 1) {
            minute = "0" + minute;
        }
        if (second.length == 1) {
            second = "0" + second;
        }
        var dateTime = year + "-" + month + "-" + day +" "+ hour +":"+minute+":"+second;
        return dateTime;
    };

    // 比较两个时间的大小
    this.compareDate = (date1, date2, type = 'date') => {
        let d1,d2;
        if(type == 'date'){}
            d1 = moment(date1).format('YYYY/MM/DD');
            d2 = moment(date1).format('YYYY/MM/DD');
        if(type == 'dateTime'){
            d1 = moment(date1).format('YYYY/MM/DD HH:mm:ss');
            d2 = moment(date1).format('YYYY/MM/DD HH:mm:ss');
        }
        let d1_s = Date.parse(d1_s);
        let d2_s = Date.parse(d2_s);
        if(d1_s > d2_s){
            return false;
        }else{
            return true;
        }
    }
    
    // 路由跳转
    this.gotoPage = (path, query) =>{
        let params = {path: path};
        if(query){
            params.query = query;
        }
        router.push(params);
    };

    // 路由跳转
    this.goto = function(url, params = {}, delay = 0) {
        let default_params = {path: url};
        let new_params = Object.assign(default_params,params);
		setTimeout(function() {
			router.push(new_params);
		}, delay);
	};

    // 关闭弹窗，弹窗内的表单初始化
    this.resetForm = (form, reset_form) => {
        let obj = JSON.parse(JSON.stringify(reset_form));
        for(var key in form){
            if(reset_form.hasOwnProperty(key)){
                form[key] = obj[key];
            };
        }
    };

    // 时间格式兼容性转换
    this.getTime = (data) => {
        let new_date = data.replace(/-/g,"/");
        let time = new Date(new_date).getTime();
        return time;
    };

    // 小时和分钟的格式,小于10的前面加0
    this.changeTimeFormat = (value) => {
        if(value > 10){
            return value;
        }else{
            return '0'+value;
        }
    };

    // 获取名字
    this.setName = (id, list = [], opt = {id: 'id', name: 'name'}) => {
        let name = '';
        let arr = list.filter(item => item[opt.id]== id);
        if(arr.length == 1){
            name = arr[0][opt.name];
        }
        return name;          
    }

    //数组格式转化
    this.transformArray = (arr, idKey, nameKey) => {
        let id = idKey || 'value';
        let name = nameKey || 'label';
        let data = [];
        if(arr.length  > 0){
            data = arr.map(item => {
               item.id = item[id];
               item.name = item[name];
               return item;
            });
        }else{
            data = []
        }
        return data;
    },

    //对象转数组
    this.objectToArray = (obj1, obj2)=>{
        let arr = [];
        for(let key in obj1){
            arr.push({name: obj1[key], value: obj2[key]})
        }
        return arr;
    }
    // 将数值按某个key，相同的排在一起
    this.sortArray = (arr, key) => {
		let new_arr = [];
		function compare(arr_sub){
			let arr1 = [];
			arr_sub.forEach((item,index) => {
				if(index == 0){
					new_arr.push(item);
					arr1.push(item);
				}else{
					if(item[key] == arr1[0][key]){
						new_arr.push(item);
						arr1.push(item);
					}
				}
			});		
			let arr2 = arr_sub.filter(item => item[key] != arr1[0][key]);
			if(new_arr.length < arr.length){
				compare(arr2, key);
			}
		}
		compare(arr);
		return new_arr;
    }

    //先清空数组，再重新添加数组，使得视图能更新
    this.resetArray = (arr, data) => {
        arr.splice(0, arr.length);
        data.forEach(item => {
            arr.push(item);
        })
    }

    //多用于select表单，通过id获取对应的name
    this.selectName = (val, arr, keyId, keyName) =>{
        let key_id = keyId || 'id';
        let key_name = keyName || 'name';
        let obj = arr.find(item => item[key_id] == val);
        if(obj){
            return obj[key_name];
        }else{
            return null;
        }        
    }

    // 根据身份证获取对应的出生日期，年龄，性别
    this.analysisIdNo = (IdCardNO) => {
        let res = {
            age: null,
            birth: null,
            sex: null,
        }
        // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
        var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (reg.test(IdCardNO) === false)
        {
            Message.warning("身份证号输入不合法");
            return res;
        }
        var date = new Date();
        var yearfull = date.getFullYear();
        if (IdCardNO.length == 18)//18位身份证号处理
        {
            var birthyear = IdCardNO.substring(6, 10);
            var month = IdCardNO.substring(10, 12);
            var day = IdCardNO.substring(12, 14);
            var age = yearfull - birthyear;
            var sexValue = IdCardNO.substring(16, 17);
            var sex = (sexValue % 2 == 0 ? "女" : "男");
            if (sex.toString() == "女")
                sexValue = "2";
            if (sex.toString() == "男")
                sexValue = "1";
            else sexValue = "0";
           res.age = age;
           res.sex = sexValue;
           res.birth = birthyear + '-' + month + '-' + day;
        }
        if (IdCardNO.length == 15)//15位身份证号处理
        {
            var birthyear = '19'+IdCardNO.substring(6, 8);
            var month = IdCardNO.substring(8, 10);
            var day = IdCardNO.substring(10, 12);
            var birthDay = "";
            birthDay = IdCardNO.substring(6, 12);
            birthDay = "19" + birthDay;
            birthDay = birthDay.substring(0, 4);// + "-" + birthDay.substring(4, 6) + "-" + birthDay.substring(6)
            var age = yearfull - birthDay;//年龄
            var sex = parseInt(birthDay.substring(14, 1), 10) % 2 ? "男" : "女";//性别
            var sexValue = "";
            if (sex.toString() == "女")
                sexValue = "2";
            if (sex.toString() == "男")
                sexValue = "1";
            else sexValue = "0";
            res.age = age;
            res.sex = sexValue;
            res.birth = birthyear + '-' + month + '-' + day;            
        }
        return res;
    };

    this.getJsBarcode = (dom,code) =>{
        JsBarcode(dom,code,{
            format:"CODE128",//条形码的格式
            width:1,//线宽
            height:30,//条码高度
            lineColor:"#000",//线条颜色
            displayValue:false,//是否显示文字
            margin:2//设置条形码周围的空白区域
        })
      },

    //获取文件url
    this.getUrl = (url) => {
        // if(url){
        //     if(url.indexOf('http') == -1){
        //         return fileUrl + url;
        //     }
        // }
        return url;
    }

    //新窗口打开url
    this.winOpen = (url) => {
        window.open(baseUrl+url);
    }

    this.fieldRequired = (arr) => {
        try {
            arr.forEach( item => {
                if(item.fieldRequired == '1' && !item.fieldValue){
                    Message.warning(item.fieldName+'为必填项！');
                    throw Error();
                }
            })
        } catch(e){
            return false;
        }
        return true;
    }
    //获取树形列表
    this.getTreeList=(data, opt)=>{
        let params = {
        id: 'id',
        parentId: 'parentId',
        name: 'name',
        };
        if(opt){
        this.resetForm(params,opt);
        }
        let newData = JSON.parse(JSON.stringify(data));
        newData.forEach((item,index) => {
            let arr = newData.filter(child => child[params.parentId] == item[params.id]);
            if(arr.length > 0){
                newData[index].children = arr.map(item => {
                    item.id = item[params.id];
                    item.parentId = item[params.parentId];
                    item.name = item[params.name];
                    return item;
                });
            }
        });
        let tree = newData.filter(item => item[params.parentId] == 0);
            tree = tree.map( item => {
            item.id = item[params.id];
            item.parentId = item[params.parentId];
            item.name = item[params.name];
            return item;
        });
        return tree;
    },
    // 关闭路由标签页
    this.closeTag = (path, type) => {  // type: 0 只关闭，-1返回上一页，1返回前一个tag
        let tagList = store.getters.tagList;
          let { tag, key } = this.findTag(path);
          store.commit('DEL_TAG', tag);
          if(type == -1){
            router.go(-1);
          }else if(type == 1){
            if (tag.value === store.getters.tag.value) {
              tag = tagList[key === 0 ? key : key - 1] // 如果关闭本标签让前推一个
              this.openTag(tag)
            }
          }          
      };
    this.openTag = (item) => {
        let tag
        if (item.name) {
          tag = this.findTag(item.name).tag
        } else {
          tag = item
        }
        router.push({
          path: router.$avueRouter.getPath({
            name: tag.label,
            src: tag.value
          }),
          query: tag.query
        }).catch(() => {})
      };
    this.findTag = (value) => {
        let tagList = store.getters.tagList;
        let tag, key
        tagList.map((item, index) => {
          if (item.value === value) {
            tag = item
            key = index
          }
        })
        return { tag: tag, key: key }
      };
      
      // 加密处理
      this.encryp = (data) =>{
        if( typeof data === "object" ){
            // 如果传入的data是json对象，先转义为json字符串
            try {
                data = JSON.stringify(data)
            } catch (error) {
                console.log("error:",error)
            }
        }
        let key = 'pigxpigxpigxpigx';
        let iv = CryptoJS.enc.Latin1.parse(key);
         // 统一将传入的字符串转成UTF8编码
        const dataHex = CryptoJS.enc.Utf8.parse( data ) // 需要加密的数据
        const keyHex = CryptoJS.enc.Utf8.parse( key ) // 秘钥
        const ivHex = CryptoJS.enc.Utf8.parse( iv ) // 偏移量
        const encrypted = CryptoJS.AES.encrypt( dataHex , keyHex , {
          iv: ivHex,
          mode: CryptoJS.mode.CBC, // 加密模式
          padding: CryptoJS.pad.Pkcs7
        })
        let encryptedVal = encrypted.ciphertext.toString()
        return encryptedVal //  返回加密后的值
    }
    
    //浏览器全屏

    this.reqFullScreen = () => {
        if (document.documentElement.requestFullScreen) {
        document.documentElement.requestFullScreen();
        } else if (document.documentElement.webkitRequestFullScreen) {
        document.documentElement.webkitRequestFullScreen();
        } else if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
        }
    };
   //浏览器退出全屏
    this.exitFullScreen = () => {
        if (document.documentElement.requestFullScreen) {
        document.exitFullScreen();
        } else if (document.documentElement.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
        } else if (document.documentElement.mozRequestFullScreen) {
        document.mozCancelFullScreen();
        }
    };

    this.exportExcel = (url, params, fileName) => {
        let opt = {};
        for(let key in params){
            if(params[key]){
                opt[key] = params[key]
            }
        };
        const loading = Loading.service({
            lock: true,
            text: '下载中，请稍等',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        request('get', url, opt, (data,msg) => {
            const blob = data.data;
            if (blob && blob.size === 0) {
              this.$notify.error("内容为空，无法下载");
              return;
            }
            const link = document.createElement("a");
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName + '.xlsx';
            document.body.appendChild(link);
            link.click();
            window.setTimeout(function() {
              window.URL.revokeObjectURL(blob);
              document.body.removeChild(link);
            }, 0); 
            loading.close(); 
        }, msg => {
            loading.close(); 
        }, {responseType: 'blob'}, 'all')
    }
    

    
}

export default new util;